package com.aplink.generic.network;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;

import com.aplink.generic.constant.HandlerConstant;
import com.aplink.generic.util.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Locale;

public class DownloadManager extends
        AsyncTask<String, Integer, ArrayList<String>> {
    private String mLocalPath;
    private ProgressDialog mProgress;
    private Context mContext;
    private Handler mHandler;
    private LogUtil mLogUtil = new LogUtil( getClass() );

    public DownloadManager( Context context, Handler handler, String localPath ) {
        mContext = context;
        mHandler = handler;
        mLocalPath = localPath;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgress = new ProgressDialog( mContext );
        mProgress.setCancelable( false );
        mProgress.setCanceledOnTouchOutside( false );
        mProgress.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
        mProgress.setProgress( 0 );
        mProgress.setMessage( "File downloading ..." );
        mProgress.setMax( 100 );
        mProgress.show();
    }

    @Override
    protected void onProgressUpdate( Integer... values ) {
        super.onProgressUpdate( values );
        mProgress.setProgress( values[0] );
        if ( values.length > 1 ) {
            mProgress.setMessage( "File downloading ..." + ( values[1] + 1 ) + "/"
                    + values[2] );
        }
    }

    @Override
    protected ArrayList<String> doInBackground( String... params ) {
        ArrayList<String> localPaths = new ArrayList<String>();
        for ( int i = 0 ; i < params.length ; i++ ) {
            try {
                String physicalPath = params[i];
                URL url = new URL( physicalPath );
                URLConnection connection = url.openConnection();
                int fileSize = connection.getContentLength();
                int currentSize = 0;
                InputStream input = connection.getInputStream();

                publishProgress( 0, i, params.length );

                String temporaryName = String.format( Locale.getDefault(),
                        "%d.jpg", System.currentTimeMillis() );
                File storagePath = new File( mLocalPath, temporaryName );
                OutputStream output = new FileOutputStream( storagePath );
                try {
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    while ( ( bytesRead = input.read( buffer, 0, buffer.length ) ) >= 0 ) {
                        output.write( buffer, 0, bytesRead );
                        currentSize += 1024;
                        float percent = (float) currentSize / (float) fileSize;
                        publishProgress( (int) ( percent * 100 ) );
                    }
                    mLogUtil.info(
                            "downloaded: " + "file://" + storagePath.toString(),
                            "Download file:" + params[i] );
                    localPaths.add( storagePath.toString() );
                } finally {
                    output.close();
                }
            } catch ( IOException e ) {
                mLogUtil.error( e.getMessage(), "Download file:" + params[i], e );
                e.printStackTrace();
            }
        }
        return localPaths;
    }

    @Override
    protected void onPostExecute( ArrayList<String> result ) {
        super.onPostExecute( result );
        mProgress.dismiss();
        mHandler.obtainMessage( HandlerConstant.DOWNLOAD_FILE_RESULT, result )
                .sendToTarget();
    }

}
